﻿using System;
using System.Linq;
using System.Windows.Forms;
using AppLoger.Abstract;
using Core.DependencyInjection;
using Core.Enum;
using System.Web;
using DHelpers.ExtensionsHelper;
using DounloderV2WinFormsUI.Properties;

namespace DounloderV2WinFormsUI.Forms
{
    public partial class WebLoginForms : Form
    {
        public event EventHandler<EventArgs> OnLogin;

        protected virtual void OnLoginEvent(object sender, EventArgs e)
        {
            e.Raise(sender, ref OnLogin);
        }

        private const int AppId = 3259026;

        private int Scopes
        {
            get
            {
                return ExtensionEnumHelper.GetEnumValuesAndDescription<ScopeVk>().Sum(t => (int) t.Key);
            }
        }

        private readonly IAppLoger _loger = NinjectFactory.Resolve<AppLoger.Implementation.AppLoger>();

        private string UrlOauch
        {
            get
            {
                return 
                string.Format(
                    "https://oauth.vk.com/authorize?client_id={0}&scope={1}&redirect_uri={2}&display=page&response_type=token",
                    AppId, Scopes, "http://oauth.vk.com/blank.html");
            }
        }

        public WebLoginForms()
        {
            InitializeComponent();
            Load += OnLoad;
            webBrowser.Navigated += WebBrowserOnNavigated;
            Text = Resources.LoginFormsText;
        }

        public override sealed string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }

        private void OnLoad(object sender, EventArgs e)
        {
            webBrowser.Navigate(UrlOauch);
        }

        private void WebBrowserOnNavigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            try
            {
                var nameValueCollection = HttpUtility.ParseQueryString(e.Url.Fragment.Substring(1));
                if (!nameValueCollection.AllKeys.Contains("access_token"))
                    return;
                Visible = false;
                Close();
                OnLoginEvent(nameValueCollection, new EventArgs());
            }
            catch (Exception ex)
            {
                _loger.Warn(ex.Message);
            }
        }
    }
}
